from PyQt5.QtCore import pyqtSignal, QObject, pyqtSlot
from src.utils.downloader import Downloader


class DownloadWorker(QObject):
    progress_signal = pyqtSignal(int, int)
    log_signal = pyqtSignal(str)
    finished = pyqtSignal()

    def __init__(self, urls, out_dir, max_workers=4):
        super().__init__()
        self.urls = urls
        self.out_dir = out_dir
        self.max_workers = max_workers
        self.downloader = None

    def cancel(self):
        if self.downloader:
            self.downloader.cancel()

    @pyqtSlot()
    def start(self):
        try:
            self.downloader = Downloader(self.urls, self.out_dir, max_workers=self.max_workers)
            self.downloader.progress_signal.connect(self.progress_signal.emit)
            self.downloader.log_signal.connect(self.log_signal.emit)
            self.downloader.start()
        except Exception as e:
            self.log_signal.emit(f"[ERROR] 下载任务失败: {e}")
        finally:
            self.finished.emit()